<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width" />

    <style>
      body { font-family: Tahoma, Geneva, sans-serif; }
    </style>

    <!-- colyseus.js client -->
    <script type="text/javascript" src="https://unpkg.com/colyseus.js@^0.14.0/dist/colyseus.js"></script>

  </head>
  <body>
    <h1>
      <a href="https://github.com/colyseus/colyseus-examples"><img src="https://cdn.jsdelivr.net/gh/colyseus/colyseus@master/media/header.png" height="100" alt="colyseus" /></a>
    </h1>

    <p>This example shows how to use</p>
    <ul>
        <li><code>allowReconection()</code> - server-side</li>
        <li><code>reconnect()</code> - client-side</li>
    </ul>
    <p>...to reestablish a connection into a <code>Room</code>.</p>

    <p>Open Developer Tools for log messages.</p>

    <p><strong>Commands</strong></p>

    <button onclick="join()">join room</button>
    <button onclick="leave()">forcibly close room connection</button>
    <button onclick="reconnect()">reconnect</button>

    <script>
      var host = window.document.location.host.replace(/:.*/, '');
      var client = new Colyseus.Client(location.protocol.replace("http", "ws") + "//" + host + (location.port ? ':' + location.port : ''));
      var room;

      function join () {
        // Logged into your app and Facebook.
        client.joinOrCreate("reconnection").then(room_instance => {
            room = room_instance;
            onjoin();
            console.log("Joined successfully!");

        }).catch(e => {
            console.error("Error", e);
        });
      }

      function onjoin() {
          room.onMessage("status", (message) => console.log(message));
          room.onLeave(() => console.log("Bye, bye!"));

          localStorage.setItem("roomId", room.id);
          localStorage.setItem("sessionId", room.sessionId);
      }

      function leave() {
        if (room) {
          room.connection.close();

        } else {
          console.warn("Not connected.");
        }
      }

      function reconnect() {
        var roomId = localStorage.getItem("roomId");
        var sessionId = localStorage.getItem("sessionId");

        client.reconnect(roomId, sessionId).then(room_instance => {
            room = room_instance;
            onjoin();
            console.log("Reconnected successfully!");
        }).catch(e => {
            console.error("Error", e);
        });

      }
    </script>

  </body>
</html>
